<template>
  <div class="app-container">
    <el-form
      :model="searchParams"
      ref="searchForm"
      :inline="true"
      v-show="showSearch"
      label-position="left"
      label-width="110px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="爬虫配置ID" prop="configId">
            <el-input
              v-model="searchParams.configId"
              placeholder="请输入ID"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-circle-plus-outline"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['template:management:add']"
          >添加字段</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['template:management:remove']"
          >删除字段</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-circle-close"
          size="medium"
          :loading="exportLoading"
          @click="handleClose"
          v-hasPermi="['template:management:export']"
          >关闭</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="spiderFieldTableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="字段ID"
        width="120"
        align="center"
        prop="fieldId"
      />
      <el-table-column
        label="爬虫配置ID"
        width="120"
        align="center"
        prop="configId"
      />
      <el-table-column label="字段" align="center" prop="field" />
      <el-table-column label="字段名称" align="center" prop="fieldName" />
      <el-table-column label="提取类型" align="center" prop="extractType">
        <template slot-scope="scope">
          <span v-if="scope.row.extractType === 'css'">Css</span>
          <span v-if="scope.row.extractType === 'xpath'">Xpath</span>
          <span v-if="scope.row.extractType === 'constant'">常量</span>
        </template>
      </el-table-column>
      <el-table-column
        label="提取规则"
        width="350"
        align="center"
        prop="extractBy"
      />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['template:management:edit']"
            >编辑</el-button
          >
          <el-button
            size="medium"
            type="text"
            icon="el-icon-s-management"
            @click="goConfigRule(scope.row)"
            v-hasPermi="['template:management:detail']"
            >配置规则</el-button
          >
          <el-button
            size="medium"
            type="text"
            icon="el-icon-delete-solid"
            @click="handleDelete(scope.row)"
            v-hasPermi="['template:management:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="searchParams.pageNum"
      :limit.sync="searchParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改爬虫字段对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字段" prop="field">
          <el-input v-model="form.field" placeholder="请输入字段" />
        </el-form-item>
        <el-form-item label="字段名称" prop="fieldName">
          <el-input v-model="form.fieldName" placeholder="请输入字段名称" />
        </el-form-item>
        <el-form-item label="提取类型" prop="extractType">
          <el-radio-group v-model="form.extractType">
            <el-radio label="xpath">Xpath</el-radio>
            <el-radio label="css">Css</el-radio>
            <el-radio label="constant">常量</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="form.extractType === 'xpath' || form.extractType === 'css'"
          label="提取规则(xpath,css值)"
          prop="extractBy"
        >
          <el-input v-model="form.extractBy" placeholder="请输入提取规则" />
        </el-form-item>

        <el-form-item
          v-if="form.extractType === 'css'"
          label="元素的索引"
          prop="extractIndex"
        >
          <el-input
            v-model="form.extractIndex"
            placeholder="请输入元素的索引"
          />
        </el-form-item>
        <el-form-item
          v-if="form.extractType === 'css'"
          label="根据属性取值"
          prop="extractAttrFlag"
        >
          <el-switch
            v-model="form.extractAttrFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item
          v-if="form.extractAttrFlag === 1"
          label="属性名"
          prop="extractAttr"
        >
          <el-input v-model="form.extractAttr" placeholder="请输入属性名" />
        </el-form-item>
        <el-form-item
          v-if="form.extractType === 'constant'"
          label="常量值"
          prop="constantValue"
        >
          <el-input v-model="form.constantValue" placeholder="请输入常量值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  querySpiderField,
  delSpiderField,
  addSpiderField,
  updateSpiderField
} from '@/api/crawler/crawler'

export default {
  name: 'SpiderField',
  components: {},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 爬虫字段表格数据
      spiderFieldTableData: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      searchParams: {
        pageNum: 1,
        pageSize: 10,
        configId: ''
      },
      // 表单参数
      form: {
        extractType: ''
      },
      // 表单校验
      rules: {}
    }
  },
  created() {
    const dictId = this.$route.params && this.$route.params.rowId
    this.searchParams.configId = Number(dictId)
    this.getList()
  },
  methods: {
    /** 查询爬虫字段列表 */
    getList() {
      this.loading = true
      querySpiderField(this.searchParams).then(response => {
        this.spiderFieldTableData = response.list
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        field: undefined,
        fieldName: undefined,
        extractType: 'xpath',
        extractBy: undefined,
        extractIndex: undefined,
        extractAttrFlag: undefined,
        extractAttr: undefined,
        constantValue: undefined
      }
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.searchParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('searchForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fieldId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 关闭按钮操作 */
    handleClose() {
      this.$router.go(-1)
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.form = {
        extractType: 'xpath'
      }
      this.title = '添加爬虫字段'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form = {
        fieldId: row.fieldId,
        field: row.field,
        fieldName: row.fieldName,
        extractType: row.extractType,
        extractBy: row.extractBy,
        extractIndex: row.extractIndex,
        extractAttrFlag: Number(row.extractAttrFlag),
        extractAttr: row.extractAttr,
        constantValue: row.constantValue
      }
      this.open = true
      this.title = '修改爬虫字段'
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.fieldId != null) {
            updateSpiderField(this.form)
              .then(response => {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          } else {
            this.form.configId = this.searchParams.configId
            addSpiderField(this.form)
              .then(response => {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
              .finally(() => {
                this.buttonLoading = false
              })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids.join(',')
      this.$confirm(
        '是否确认删除爬虫字段编号为"' + ids + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.loading = true
          return delSpiderField(ids)
        })
        .then(() => {
          this.loading = false
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    /** 进入配置字段页面 */
    goConfigRule(row) {
      const rowId = row.fieldId || this.ids[0]
      this.$router.push('/crawlerConfig/configRule/' + rowId)
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-dialog__footer {
  text-align: center;
}
</style>